package com.auto.survey.activity.monitoring.modle

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.auto.survey.activity.monitoring.dao.MonitoringRepository
import com.auto.survey.activity.monitoring.entity.MonitorCheckPoint
import com.auto.survey.activity.monitoring.entity.MonitorStauts
import com.auto.survey.activity.monitoring.entity.relations.PointWithCheckedPoint
import com.google.gson.Gson
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

class AutoCheckViewModle: ViewModel() {
    // 使用协程作用域处理数据库操作
    private val viewModelScope = CoroutineScope(Dispatchers.IO + SupervisorJob())

    val state = MutableLiveData<MonitorStauts>()
    val mirrorType = MutableLiveData<String>()
    val measureModle = MutableLiveData<String>()

    // 处理检查点数据
    val mupdata = MutableLiveData<List<PointWithCheckedPoint>>()

    fun updateMonitorCheckPoint(checkPoint: MonitorCheckPoint, database: MonitoringRepository, stationId:Int) {
        viewModelScope.launch {
            try {

                Log.w("AutoCheckActivity", "新增核验数据 checkPoint = ${Gson().toJson(checkPoint)}")
                val point = database.getMonitoringPointById(checkPoint.pointId)
                if (point != null) {
                    val pass = point.hasSameCoordinates(checkPoint)
                    checkPoint.isPass = pass
                    Log.w("AutoCheckActivity", "新增核验数据 isPass = $pass")
                    val insertRlt = database.createCheckPoint(checkPoint)
                    if (insertRlt != -1L) {
                        database.getCollectedPointsWithCheckedPointsByStationId(stationId).collect{
                            mupdata.postValue(it) // 使用postValue确保在主线程更新
                        }
                    }
                }

            } catch (e: Exception) {
                Log.e("AutoCheckActivity", "更新检查点失败", e)
            }
        }
    }


    fun updateState(stauts:MonitorStauts) {
        state.postValue(stauts)
    }

    fun updateMirrorType(type:String){
        mirrorType.postValue(type)
    }

    fun updateMeasureModle(modle:String){
        viewModelScope.launch {
            measureModle.postValue(modle)
        }
    }

    // ViewModel 销毁时取消协程
    override fun onCleared() {
        super.onCleared()
        viewModelScope.cancel()
    }
}